import { Button, Color, EventHandler, instantiate, Label, Node, Toggle, ToggleContainer } from "cc";
import { Util } from "../../../Util";
import { MyEvent } from "../event/MyEvent";
import { ViewCtrlBase } from "./ViewCtrlBase";


export abstract class ViewBase {

    protected _viewCtrl: any;

    protected _node: Node;

    abstract get myViewCtrl(): any;

    set viewCtrl(ctrl: any) {
        this._viewCtrl = ctrl;
    }

    get node(): Node {
        return this._node;
    }
    set node(val: Node) {
        this._node = val;
    }

    private _menu: Node = null;
    get menu(): Node {
        return this._menu;
    }

    btn_close: Node = null;

    constructor(

    ) {

    }

    onCreate(): void {
        this.bindNode();
    }

    protected bindNode(): void {
        this.btn_close = Util.ins.render.searchChild(this.node, "btn_close");
    }

    protected unBindNode(): void {
        this.btn_close = null;
    }

    destroy() {
        this._menu = null;
        this.unBindNode();
        this.node.isValid && this.node.destroy();
        this._node = null;
    }

    addClickEvent(btnNode: Node, handler: Function, target: any): void {
        btnNode.on(Button.EventType.CLICK, handler, target);
    }

    getNode(nodeName: string): Node {
        return this.node.getChildByName(nodeName);
    }

    createMenu(): void {
        if (this._menu) {
            return;
        }
        const menuParent = this.getNode("menu")
        if (!menuParent) {
            return;
        }
        const list = this._viewCtrl.getMenuList();
        if (!list) {
            return;
        }
        let index = 0;
        for (const id of list) {
            const itemPrefab = this.getNode("menu_item")//menuParent.getChildByName("item");
            const item = instantiate(itemPrefab);
            (item as any).bg = item.getChildByName("bg");
            (item as any).label = item.getChildByName("label");
            item.active = true;
            menuParent.addChild(item);
            (function (idx) {
                item.on(Node.EventType.TOUCH_END, () => {
                    const e = new MyEvent("node_switchPage", true, idx)
                    item.dispatchEvent(e)
                }, null);
            })(index);

            const ctrl = this._viewCtrl.viewMgr.getCtrl(id);
            (item as any).label.getComponent(Label).string = ctrl.config.label;

            index++;
        }

        this._menu = menuParent;
    }

    setMenuItemFocus(index: number, bFocus: boolean): void {
        if(!this._menu){
            return;
        }
        const item = this._menu.children[index];
        if (!item) {
            return;
        }
        (item as any).bg.active = bFocus;
        ((item as any).label as Label).getComponent(Label).color = bFocus ? Color.WHITE : Color.BLACK;
    }



}

